package ui;

import java.awt.Component;
import java.awt.GridLayout;
import java.util.Vector;

import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.ListCellRenderer;

public class MultiColumnsJList extends JList {

	Vector<Object> vectorData;
	int nbColumns;
	
	public MultiColumnsJList(int nbColumns){
		
		vectorData=new Vector<Object>();
		this.nbColumns=nbColumns;
		this.setCellRenderer(new MultiColumnCellRenderer(nbColumns));
		
	}
	
	public void modifyElement(Object[] value){
		
		int i=0;
		Object[] element=null;
		while(i<vectorData.size() && element==null){
			if (((Object[])vectorData.elementAt(i))[0].equals(value[0].toString())){
				element=(Object[])vectorData.elementAt(i);
			}
			i++;
		}
		if (element !=null){
			((Object[])element)[1]=value[1].toString();
			this.setListData(vectorData);
		}else{
			addElement(value);	
		}		
		
	}
	
	public void addElement(Object[] value){
		
		vectorData.add(value);
		this.setListData(vectorData);
				
	}

	static class MultiColumnCellRenderer extends JPanel implements ListCellRenderer{

		JLabel[] labels;
		int nbLabels;

		MultiColumnCellRenderer(int nbLabels) {
			this.nbLabels=nbLabels;
			setLayout(new GridLayout(1, nbLabels));
			labels=new JLabel[nbLabels];
			for(int i=0;i<nbLabels;i++){
				labels[i]=new JLabel();
				labels[i].setOpaque(true);
				add(labels[i]);            	        
			}
		}

		public Component getListCellRendererComponent(JList list,Object value,int index,boolean isSelected,boolean cellHasFocus){
					
			Object[] values=(Object[])value;
			
			for(int i=0;i<nbLabels;i++){
				labels[i].setText(values[i].toString());
			}
			
			if(isSelected){
				for(int i=0;i<nbLabels;i++){
					labels[i].setBackground(list.getSelectionBackground());
					labels[i].setForeground(list.getSelectionForeground());
				}				
			}else{				
				for(int i=0;i<nbLabels;i++){
					labels[i].setBackground(list.getBackground());
					labels[i].setForeground(list.getForeground());
				}				
			}
			setEnabled(list.isEnabled());
			setFont(list.getFont());
			return this;
		}
	}

}
